#!/bin/bash
# K8s部署资源提取器 Linux/Mac 启动脚本

# 切换到脚本所在目录
cd "$(dirname "$0")"

# 检查Python环境
if ! command -v python3 &> /dev/null; then
    if ! command -v python &> /dev/null; then
        echo "Error: Python command not found. Please ensure Python 3 is installed and added to PATH"
        exit 1
    fi
    PYTHON_CMD="python"
else
    PYTHON_CMD="python3"
fi

# 初始化变量
INTERACTIVE=0
CONFIG_FILE="config.yaml"
SOURCE_DIR="sources"
OUTPUT_DIR="outputs"
VERBOSE=0
FORCE_RUN=0

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case "$1" in
        -i|--interactive)
            INTERACTIVE=1
            ;;
        -c|--config)
            CONFIG_FILE="$2"
            shift
            ;;
        -s|--source)
            SOURCE_DIR="$2"
            shift
            ;;
        -o|--output)
            OUTPUT_DIR="$2"
            shift
            ;;
        -v|--verbose)
            VERBOSE=1
            ;;
        -y|--yes)
            FORCE_RUN=1
            ;;
        *)
            echo "Unknown argument: $1"
            ;;
    esac
    shift
done

# 交互模式
if [[ $INTERACTIVE -eq 1 && $FORCE_RUN -eq 0 ]]; then
    echo "Welcome to K8s Deployment Resource Extractor"
    echo "==========================================="
    
    # 源目录
    read -p "Source directory [$SOURCE_DIR]: " SOURCE_INPUT
    if [[ -n "$SOURCE_INPUT" ]]; then
        SOURCE_DIR="$SOURCE_INPUT"
    fi
    
    # 输出目录
    read -p "Output directory [$OUTPUT_DIR]: " OUTPUT_INPUT
    if [[ -n "$OUTPUT_INPUT" ]]; then
        OUTPUT_DIR="$OUTPUT_INPUT"
    fi
    
    # 配置文件
    read -p "Configuration file [$CONFIG_FILE]: " CONFIG_INPUT
    if [[ -n "$CONFIG_INPUT" ]]; then
        CONFIG_FILE="$CONFIG_INPUT"
    fi
    
    # 详细日志模式
    read -p "Enable verbose logging? (y/N): " VERBOSE_INPUT
    if [[ "$VERBOSE_INPUT" == "y" || "$VERBOSE_INPUT" == "Y" ]]; then
        VERBOSE=1
    fi
    
    # 显示摘要
    echo
    echo "Settings Summary:"
    echo "  Source Directory: $SOURCE_DIR"
    echo "  Output Directory: $OUTPUT_DIR"
    echo "  Configuration: $CONFIG_FILE"
    if [[ $VERBOSE -eq 1 ]]; then
        echo "  Verbose: Yes"
    else
        echo "  Verbose: No"
    fi
    
    # 最终确认
    read -p $'\nStart extraction with these settings? (Y/n): ' CONFIRM
    if [[ "$CONFIRM" == "n" || "$CONFIRM" == "N" ]]; then
        echo "Extraction cancelled by user"
        exit 0
    fi
fi

# 构建命令参数
ARGS="--source \"$SOURCE_DIR\" --output \"$OUTPUT_DIR\" --config \"$CONFIG_FILE\""
if [[ $VERBOSE -eq 1 ]]; then
    ARGS="$ARGS --verbose"
fi

# 启动应用程序
echo "Starting K8s Deployment Resource Extractor..."
$PYTHON_CMD -m src $ARGS

# 检查退出状态
EXIT_CODE=$?
if [[ $EXIT_CODE -ne 0 ]]; then
    echo "Application exited with error code: $EXIT_CODE"
    exit $EXIT_CODE
fi

exit 0